<template>
  <div>
    <el-form label-width="80px">
      <el-form-item label="添加地区" v-if="isAll">
        <el-checkbox v-model="isAllChecked" :indeterminate="isIndeterminate"
          @change="handleAllCheckedChange">全选</el-checkbox>
      </el-form-item>
      <el-checkbox-group v-model="checkedArea" @change="handleCheckedAreaChange">
        <el-form-item v-for="(value, key) in groupData" :label="key" :key="key">
          <el-checkbox v-for="area in value" :disabled="areaNma.includes(area.area_name)"
            :key="area.area_code" :label="area">{{ area.area_name }}</el-checkbox>
        </el-form-item>
      </el-checkbox-group>
    </el-form>
  </div>
</template>

<script setup>
import { useAreaGroup } from '../Hooks/freightAction'
import { useFreightAction } from '../Hooks/freightAction'
const props = defineProps({
  groupProvince: {
    type: Object,
    default: () => ({})
  },
  isAll: {
    type: Boolean,
    default: true
  },
  modelValue: {
    type: Array,
    default: []
  },
  // 已选中的全部地区名 取的area_name
  prevAreaData: {
    type: Array,
    default: []
  },
})
const { isEditFreight, itemDesignatedArea } = useFreightAction()
// 排除掉自身已选中的值
const areaNma = computed(() => {
  const arr = itemDesignatedArea.value?.destination?.split('，') ?? []
  return props.prevAreaData.filter(item=>!arr.includes(item))
})

const { group, province } = useAreaGroup()
const groupData = computed(() => {
  const length = Object.keys(props.groupProvince).length
  return length ? props.groupProvince : group
})
const emit = defineEmits(['update:modelValue'])
const checkedArea = ref([])
// TODO:待验证
watch(() => props.modelValue, (newVal) => {
  if (!newVal.length) {
    isAllChecked.value = false
    isIndeterminate.value = false
  } else if (newVal.length === province.length) {
    isAllChecked.value = true
    isIndeterminate.value = false
  } else {
    isIndeterminate.value = true
  }
  checkedArea.value = newVal
})
const isAllChecked = ref(false)
const isIndeterminate = ref(false)
const handleAllCheckedChange = (val) => {
  const a = province.filter(item => !areaNma.value.includes(item.area_name))
  checkedArea.value = val ? a : []
  isIndeterminate.value = false
  emit('update:modelValue', checkedArea.value)
}
const handleCheckedAreaChange = (val) => {
  const checkedCount = val.length;
  isAllChecked.value = checkedCount === province.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < province.length;
  emit('update:modelValue', checkedArea.value)
}
const rest = () => {
  checkedArea.value = []
  isAllChecked.value = false
  isIndeterminate.value = false
}
defineExpose({
  rest
})
</script>

<style lang="less" scoped></style>